package com.linkai.JUC._03_lock8;

import java.util.concurrent.TimeUnit;

/**
 * @Description: 死锁
 *                死锁的排除；
 *               （1）jps -l 定位进程号
 *               （2）jstack 进程号查看进程信息，之后就会显示出现死锁的代码行数
 * @Author: 林凯
 * @Date: 2021/10/26 23:30
 */
public class DeadLockDemo {
    public static void main(String[] args) {
        String lockA = "lockA";
        String lockB = "lockB";

        // T1 会先获得A的锁，等待2s之后，尝试获取B的锁
        new Thread(new MyThread(lockA, lockB), "T1").start();
        // T2 会先获得B的说，等待2s之后，尝试获取A的锁
        new Thread(new MyThread(lockB, lockA), "T2").start();
        /*
            T1lock:lockA->get lockB
            T2lock:lockB->get lockB
        * */
    }
}

class MyThread implements Runnable {

    private String lockA;
    private String lockB;

    public MyThread(String lockA, String lockB) {
        this.lockA = lockA;
        this.lockB = lockB;
    }

    @Override
    public void run() {
        synchronized (lockA) {
            System.out.println(Thread.currentThread().getName() + "lock:" + lockA + "->get lockB");

            try {
                // 设置一个延时，确保T1线程拿到A的说，T2线程拿到B的锁
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            synchronized (lockB) {
                System.out.println(Thread.currentThread().getName() + "lock:" + lockB + "->get lockA");
            }
        }
    }
}
